package server;

import java.nio.charset.Charset;

import handler.ControlDataHandler;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

public class ControlServerHandler extends ChannelInboundHandlerAdapter {
	
	static ChannelHandlerContext ctx1;
	
	/**
     * 网络连接时调用
     */
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("客户端："+ctx.channel().remoteAddress()+" 连接到服务器:"+ctx.channel().localAddress());
		ctx.writeAndFlush(Unpooled.copiedBuffer("Welcome to connect the Server:",CharsetUtil.UTF_8));
		ctx1 = ctx;
		super.channelActive(ctx);
	}
	/**
     * 网路连接失活时调用
     */
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("客户端："+ctx.channel().remoteAddress()+"与服务器断开连接");
		super.channelInactive(ctx);
	}
	/**
     * 读取数据时调用
     * 实现Json数据解析和数据库操作
     */
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
				ByteBuf buf = (ByteBuf) msg;		// 将msg转成ByteBuf对象
				String body = null;
				ControlDataHandler controldata = new ControlDataHandler();

				try{
					int len = buf.readableBytes();  //获取缓冲区可读字节数
					body = buf.readBytes(len).toString(Charset.forName("UTF-8"));
					controldata.Datahandle(body);
					
				}catch(Exception e){
					e.printStackTrace();	
				}
		
	}
	/**
     * 读写完成调用
     */
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		super.channelReadComplete(ctx);
	}
	/**
	 * 心跳机制实现自动获取
	 */
	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		ctx.writeAndFlush(Unpooled.copiedBuffer("Select all data",CharsetUtil.UTF_8));
		super.userEventTriggered(ctx, evt);
	}
    /**
     * 捕捉到异常调用
     */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		System.out.println("客户端："+ctx.channel().remoteAddress()+"发生异常与服务器断开连接");
		super.exceptionCaught(ctx, cause);
	}
	/**
	 * 实现连接信息传输
	 */
	public static ChannelHandlerContext Get(){
		return ctx1;
	}

}
